package com.freeter.modules.gjs.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.freeter.common.exception.RRException;
import com.freeter.modules.gjs.entity.MstrCat01;
import com.freeter.modules.gjs.mapper.MstrCat01Mapper;
import com.freeter.modules.gjs.service.MstrCat01Service;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class MstrCat01ServiceImpl implements MstrCat01Service {
    
    private static final Logger logger = LoggerFactory.getLogger(MstrCat01ServiceImpl.class);
    
    @Autowired
    private MstrCat01Mapper mstrCat01Mapper;

    @Override
    public List<MstrCat01> listAll() {
        try {
            Wrapper<MstrCat01> wrapper = new EntityWrapper<>();
            wrapper.eq("is_deleted", 0);
            wrapper.orderBy("plevel", true).orderBy("id", true);
            return mstrCat01Mapper.selectList(wrapper);
        } catch (Exception e) {
            logger.error("获取所有二级分类信息失败", e);
            throw new RRException("获取二级分类信息失败：" + e.getMessage());
        }
    }

    @Override
    public MstrCat01 getById(Long id) {
        if (id == null || id <= 0) {
            logger.warn("二级分类ID不能为空或负数: {}", id);
            return null;
        }
        
        try {
            Wrapper<MstrCat01> wrapper = new EntityWrapper<>();
            wrapper.eq("id", id).eq("is_deleted", 0);
            List<MstrCat01> categories = mstrCat01Mapper.selectList(wrapper);
            return categories.isEmpty() ? null : categories.get(0);
        } catch (Exception e) {
            logger.error("根据ID获取二级分类信息失败, id: {}", id, e);
            throw new RRException("获取二级分类信息失败：" + e.getMessage());
        }
    }

    @Override
    public List<MstrCat01> getByPlevel(Long plevel) {
        if (plevel == null || plevel <= 0) {
            logger.warn("父级分类ID不能为空或负数: {}", plevel);
            return null;
        }
        
        try {
            Wrapper<MstrCat01> wrapper = new EntityWrapper<>();
            wrapper.eq("plevel", plevel).eq("is_deleted", 0);
            wrapper.orderBy("id", true);
            return mstrCat01Mapper.selectList(wrapper);
        } catch (Exception e) {
            logger.error("根据父级ID获取二级分类列表失败, plevel: {}", plevel, e);
            throw new RRException("获取二级分类列表失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(MstrCat01 entity) {
        if (entity == null) {
            logger.warn("二级分类实体不能为空");
            throw new RRException("二级分类实体不能为空");
        }
        
        try {
            if (entity.getIsDeleted() == null) {
                entity.setIsDeleted(0);
            }
            
            validateEntity(entity);
            
            if (entity.getId() != null) {
                MstrCat01 existingCategory = mstrCat01Mapper.selectById(entity.getId());
                if (existingCategory != null) {
                    logger.warn("二级分类ID已存在: {}", entity.getId());
                    throw new RRException("二级分类ID已存在：" + entity.getId());
                }
            }
            
            int result = mstrCat01Mapper.insert(entity);
            if (result <= 0) {
                logger.error("创建二级分类失败");
                throw new RRException("创建二级分类失败");
            }
            
            logger.info("二级分类创建成功, id: {}", entity.getId());
        } catch (RRException e) {
            throw e;
        } catch (Exception e) {
            logger.error("创建二级分类异常", e);
            throw new RRException("创建二级分类失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(MstrCat01 entity) {
        if (entity == null || entity.getId() == null) {
            logger.warn("二级分类实体或ID不能为空");
            throw new RRException("二级分类实体或ID不能为空");
        }
        
        try {
            validateEntity(entity);
            
            MstrCat01 existingCategory = mstrCat01Mapper.selectById(entity.getId());
            if (existingCategory == null) {
                logger.warn("二级分类不存在: {}", entity.getId());
                throw new RRException("二级分类不存在：" + entity.getId());
            }
            
            if (entity.getIsDeleted() == null) {
                entity.setIsDeleted(existingCategory.getIsDeleted());
            }
            
            int result = mstrCat01Mapper.updateById(entity);
            if (result <= 0) {
                logger.error("更新二级分类失败, id: {}", entity.getId());
                throw new RRException("更新二级分类失败");
            }
            
            logger.info("二级分类更新成功, id: {}", entity.getId());
        } catch (RRException e) {
            throw e;
        } catch (Exception e) {
            logger.error("更新二级分类异常, id: {}", entity.getId(), e);
            throw new RRException("更新二级分类失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long id) {
        if (id == null || id <= 0) {
            logger.warn("二级分类ID不能为空或负数: {}", id);
            throw new RRException("二级分类ID不能为空或负数");
        }
        
        try {
            MstrCat01 existingCategory = mstrCat01Mapper.selectById(id);
            if (existingCategory == null) {
                logger.warn("二级分类不存在: {}", id);
                throw new RRException("二级分类不存在：" + id);
            }
            
            MstrCat01 updateEntity = new MstrCat01();
            updateEntity.setId(id);
            updateEntity.setIsDeleted(1);
            
            int result = mstrCat01Mapper.updateById(updateEntity);
            if (result <= 0) {
                logger.error("删除二级分类失败, id: {}", id);
                throw new RRException("删除二级分类失败");
            }
            
            logger.info("二级分类删除成功, id: {}", id);
        } catch (RRException e) {
            throw e;
        } catch (Exception e) {
            logger.error("删除二级分类异常, id: {}", id, e);
            throw new RRException("删除二级分类失败：" + e.getMessage());
        }
    }

    private void validateEntity(MstrCat01 entity) {
        if (StringUtils.isBlank(entity.getDescEn()) && 
            StringUtils.isBlank(entity.getDescHk()) && 
            StringUtils.isBlank(entity.getDescCn())) {
            logger.warn("二级分类描述不能全部为空");
            throw new RRException("二级分类描述不能全部为空");
        }
        
        if (entity.getPlevel() == null || entity.getPlevel() <= 0) {
            logger.warn("父级分类ID不能为空或负数");
            throw new RRException("父级分类ID不能为空或负数");
        }
    }
} 